<!-- 阎王殿审判记录页面 -->
<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="page-title">阎王殿审判记录</h1>
        <div class="breadcrumb-container">
          <router-link to="/" class="link link-hover">首页</router-link>
          <span class="mx-2">/</span>
          <span>阎王殿审判记录</span>
        </div>
      </div>
      <div class="btn-group">
        <button class="btn btn-primary gap-2" @click="handleNewJudgment">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V7z" clip-rule="evenodd" />
          </svg>
          新增审判
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-container grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <div class="stat bg-base-100 shadow-lg">
        <div class="stat-figure text-primary">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" viewBox="0 0 20 20" fill="currentColor">
            <path d="M9 6a3 3 0 11-6 0 3 3 0 016 0zM17 6a3 3 0 11-6 0 3 3 0 016 0zM12.93 17c.046-.327.07-.66.07-1a6.97 6.97 0 00-1.5-4.33A5 5 0 0119 16v1h-6.07zM6 11a5 5 0 015 5v1H1v-1a5 5 0 015-5z" />
          </svg>
        </div>
        <div class="stat-title">总审判数</div>
        <div class="stat-value text-primary">{{ stats.total }}</div>
        <div class="stat-desc">较上月增长 {{ stats.growth }}%</div>
      </div>

      <div class="stat bg-base-100 shadow-lg">
        <div class="stat-figure text-warning">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd" />
          </svg>
        </div>
        <div class="stat-title">待审判</div>
        <div class="stat-value text-warning">{{ stats.pending }}</div>
        <div class="stat-desc">较昨日增长 {{ stats.pendingGrowth }}%</div>
      </div>

      <div class="stat bg-base-100 shadow-lg">
        <div class="stat-figure text-info">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M6.672 1.911a1 1 0 10-1.932.518l.259.966a1 1 0 001.932-.518l-.26-.966zM2.429 4.74a1 1 0 10-.517 1.932l.966.259a1 1 0 00.517-1.932l-.966-.26zm8.814-.569a1 1 0 00-1.415-1.414l-.707.707a1 1 0 101.415 1.415l.707-.708zm-7.071 7.072l.707-.707A1 1 0 003.465 9.12l-.708.707a1 1 0 001.415 1.415zm3.2-5.171a1 1 0 00-1.3 1.3l4 10a1 1 0 001.823.075l1.38-2.759 3.018 3.02a1 1 0 001.414-1.415l-3.019-3.02 2.76-1.379a1 1 0 00-.076-1.822l-10-4z" clip-rule="evenodd" />
          </svg>
        </div>
        <div class="stat-title">处理中</div>
        <div class="stat-value text-info">{{ stats.processing }}</div>
        <div class="stat-desc">较昨日增长 {{ stats.processingGrowth }}%</div>
      </div>

      <div class="stat bg-base-100 shadow-lg">
        <div class="stat-figure text-success">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
          </svg>
        </div>
        <div class="stat-title">已完成</div>
        <div class="stat-value text-success">{{ stats.completed }}</div>
        <div class="stat-desc">较昨日增长 {{ stats.completedGrowth }}%</div>
      </div>
    </div>

    <!-- 趋势图 -->
    <div class="card bg-base-100 shadow-lg mb-6">
      <div class="card-body">
        <h2 class="card-title">审判趋势</h2>
        <div class="h-64 relative">
          <!-- 这里可以集成echarts等图表库 -->
          <div class="absolute inset-0 flex items-center justify-center text-base-content/20">
            图表区域
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="card bg-base-100 shadow-lg mb-6">
      <div class="card-body">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">关键词</span>
            </label>
            <input
              v-model="searchForm.keyword"
              type="text"
              placeholder="请输入关键词"
              class="input input-bordered"
            />
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">状态</span>
            </label>
            <select v-model="searchForm.status" class="select select-bordered">
              <option value="">全部</option>
              <option value="pending">待审判</option>
              <option value="processing">处理中</option>
              <option value="completed">已完成</option>
            </select>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">审判官</span>
            </label>
            <select v-model="searchForm.judge" class="select select-bordered">
              <option value="">全部</option>
              <option v-for="judge in judges" :key="judge" :value="judge">{{ judge }}</option>
            </select>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">时间范围</span>
            </label>
            <div class="join">
              <input
                v-model="searchForm.startTime"
                type="date"
                class="join-item input input-bordered w-[50%]"
              />
              <input
                v-model="searchForm.endTime"
                type="date"
                class="join-item input input-bordered w-[50%]"
              />
            </div>
          </div>
        </div>
        <div class="flex justify-end mt-4">
          <button class="btn btn-ghost" @click="resetSearch">重置</button>
          <button class="btn btn-primary ml-2" @click="handleSearch">搜索</button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="card bg-base-100 shadow-lg">
      <div class="card-body">
        <div class="overflow-x-auto">
          <table class="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>魂魄ID</th>
                <th>前世</th>
                <th>罪行</th>
                <th>功德值</th>
                <th>审判官</th>
                <th>审判时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="judgment in judgments" :key="judgment.id">
                <td class="font-mono text-sm">{{ judgment.id }}</td>
                <td class="font-mono text-sm">{{ judgment.soulId }}</td>
                <td>{{ judgment.previousLife }}</td>
                <td>
                  <div class="flex flex-wrap gap-1">
                    <div
                      v-for="(crime, index) in judgment.crimes"
                      :key="index"
                      class="badge badge-sm"
                    >
                      {{ crime }}
                    </div>
                  </div>
                </td>
                <td>
                  <div class="flex items-center gap-2">
                    <div class="radial-progress" :style="{ '--value': judgment.merit, '--size': '2rem' }">
                      {{ judgment.merit }}
                    </div>
                  </div>
                </td>
                <td>{{ judgment.judge }}</td>
                <td>{{ formatDate(judgment.time) }}</td>
                <td>
                  <div class="badge" :class="getStatusBadgeClass(judgment.status)">
                    {{ getStatusLabel(judgment.status) }}
                  </div>
                </td>
                <td>
                  <div class="btn-group">
                    <button class="btn btn-ghost btn-sm" @click="handleEdit(judgment)">
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
                      </svg>
                    </button>
                    <button class="btn btn-ghost btn-sm" @click="handleDelete(judgment)">
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                      </svg>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="flex justify-between items-center mt-4">
          <div class="text-sm text-base-content/60">
            共 {{ total }} 条记录
          </div>
          <div class="join">
            <button class="join-item btn btn-sm" :disabled="currentPage === 1" @click="handlePageChange(currentPage - 1)">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
              </svg>
            </button>
            <button class="join-item btn btn-sm">{{ currentPage }} / {{ totalPages }}</button>
            <button class="join-item btn btn-sm" :disabled="currentPage === totalPages" @click="handlePageChange(currentPage + 1)">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <dialog ref="editDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">{{ isEdit ? '编辑审判' : '新增审判' }}</h3>
        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">魂魄ID</span>
            </label>
            <input
              type="text"
              v-model="form.soulId"
              placeholder="请输入魂魄ID"
              class="input input-bordered"
              :class="{ 'input-error': errors.soulId }"
            />
            <label class="label" v-if="errors.soulId">
              <span class="label-text-alt text-error">{{ errors.soulId }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">前世</span>
            </label>
            <input
              type="text"
              v-model="form.previousLife"
              placeholder="请输入前世"
              class="input input-bordered"
              :class="{ 'input-error': errors.previousLife }"
            />
            <label class="label" v-if="errors.previousLife">
              <span class="label-text-alt text-error">{{ errors.previousLife }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">罪行</span>
            </label>
            <textarea
              v-model="form.crimes"
              placeholder="请输入罪行，多个罪行用逗号分隔"
              class="textarea textarea-bordered"
              :class="{ 'textarea-error': errors.crimes }"
            ></textarea>
            <label class="label" v-if="errors.crimes">
              <span class="label-text-alt text-error">{{ errors.crimes }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">功德值</span>
            </label>
            <input
              type="number"
              v-model="form.merit"
              placeholder="请输入功德值"
              class="input input-bordered"
              :class="{ 'input-error': errors.merit }"
            />
            <label class="label" v-if="errors.merit">
              <span class="label-text-alt text-error">{{ errors.merit }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">证据</span>
            </label>
            <textarea
              v-model="form.evidence"
              placeholder="请输入证据，多个证据用逗号分隔"
              class="textarea textarea-bordered"
              :class="{ 'textarea-error': errors.evidence }"
            ></textarea>
            <label class="label" v-if="errors.evidence">
              <span class="label-text-alt text-error">{{ errors.evidence }}</span>
            </label>
          </div>
        </form>
        <div class="modal-action">
          <button class="btn btn-ghost" @click="closeDialog">取消</button>
          <button
            class="btn btn-primary"
            :class="{ loading: isSubmitting }"
            @click="handleSubmit"
          >
            确定
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>

    <!-- 删除确认对话框 -->
    <dialog ref="deleteDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg">确认删除</h3>
        <p class="py-4">确定要删除这条审判记录吗？此操作不可撤销。</p>
        <div class="modal-action">
          <button class="btn btn-ghost" @click="closeDeleteDialog">取消</button>
          <button
            class="btn btn-error"
            :class="{ loading: isDeleting }"
            @click="confirmDelete"
          >
            删除
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { formatDate } from '@/utils/date'
import { JudgmentService, type Judgment, type JudgmentStats } from '@/api/services'
import { useLoadingStore } from '@/stores/loading'
import { useToast } from '@/composables/useToast'

const loadingStore = useLoadingStore()
const toast = useToast()

// 状态
const stats = ref<JudgmentStats>({
  total: 0,
  pending: 0,
  processing: 0,
  completed: 0,
  todayCount: 0,
  weeklyTrend: [],
})

const judgments = ref<Judgment[]>([])
const currentPage = ref(1)
const total = ref(0)
const totalPages = ref(1)
const pageSize = 10

const judges = ['阎罗王', '判官王', '黑无常', '白无常']

// 搜索表单
interface SearchForm {
  keyword: string
  status: string
  judge: string
  startTime: string
  endTime: string
}

const searchForm = reactive<SearchForm>({
  keyword: '',
  status: '',
  judge: '',
  startTime: '',
  endTime: '',
})

// 编辑表单
interface Form {
  soulId: string
  previousLife: string
  crimes: string
  punishment: string
  merit: number
  evidence: string
}

interface FormErrors {
  soulId: string
  previousLife: string
  crimes: string
  punishment: string
  merit: string
  evidence: string
}

const form = reactive<Form>({
  soulId: '',
  previousLife: '',
  crimes: '',
  punishment: '',
  merit: 0,
  evidence: '',
})

const errors = reactive<FormErrors>({
  soulId: '',
  previousLife: '',
  crimes: '',
  punishment: '',
  merit: '',
  evidence: '',
})

// 对话框状态
const editDialog = ref<HTMLDialogElement | null>(null)
const deleteDialog = ref<HTMLDialogElement | null>(null)
const isEdit = ref(false)
const isSubmitting = ref(false)
const isDeleting = ref(false)
const selectedJudgment = ref<Judgment | null>(null)

// 方法
const getStatusBadgeClass = (status: string) => {
  switch (status) {
    case 'pending':
      return 'badge-warning'
    case 'processing':
      return 'badge-info'
    case 'completed':
      return 'badge-success'
    default:
      return 'badge-ghost'
  }
}

const getStatusLabel = (status: string) => {
  switch (status) {
    case 'pending':
      return '待审判'
    case 'processing':
      return '处理中'
    case 'completed':
      return '已完成'
    default:
      return '未知'
  }
}

const loadStats = async () => {
  try {
    loadingStore.show()
    const data = await JudgmentService.getStats()
    stats.value = data
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    loadingStore.hide()
  }
}

const loadJudgments = async () => {
  try {
    loadingStore.show()
    const { items, total: totalCount } = await JudgmentService.getJudgments({
      page: currentPage.value,
      pageSize,
      ...searchForm,
    })
    judgments.value = items
    total.value = totalCount
    totalPages.value = Math.ceil(totalCount / pageSize)
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    loadingStore.hide()
  }
}

const handleNewJudgment = () => {
  isEdit.value = false
  form.soulId = ''
  form.previousLife = ''
  form.crimes = ''
  form.punishment = ''
  form.merit = 0
  form.evidence = ''
  Object.keys(errors).forEach(key => {
    errors[key as keyof FormErrors] = ''
  })
  editDialog.value?.showModal()
}

const handleEdit = (judgment: Judgment) => {
  isEdit.value = true
  selectedJudgment.value = judgment
  form.soulId = judgment.soulId
  form.previousLife = judgment.previousLife
  form.crimes = judgment.crimes.join(',')
  form.punishment = judgment.punishment
  form.merit = judgment.merit
  form.evidence = judgment.evidence?.join(',') || ''
  Object.keys(errors).forEach(key => {
    errors[key as keyof FormErrors] = ''
  })
  editDialog.value?.showModal()
}

const handleDelete = (judgment: Judgment) => {
  selectedJudgment.value = judgment
  deleteDialog.value?.showModal()
}

const validateForm = () => {
  let isValid = true
  if (!form.soulId) {
    errors.soulId = '请输入魂魄ID'
    isValid = false
  }
  if (!form.previousLife) {
    errors.previousLife = '请输入前世'
    isValid = false
  }
  if (!form.crimes) {
    errors.crimes = '请输入罪行'
    isValid = false
  }
  if (!form.punishment) {
    errors.punishment = '请输入惩罚'
    isValid = false
  }
  if (form.merit < 0 || form.merit > 100) {
    errors.merit = '功德值必须在0-100之间'
    isValid = false
  }
  return isValid
}

const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  try {
    isSubmitting.value = true
    const params = {
      soulId: form.soulId,
      previousLife: form.previousLife,
      crimes: form.crimes.split(','),
      punishment: form.punishment,
      merit: form.merit,
      evidence: form.evidence ? form.evidence.split(',') : undefined,
    }

    if (isEdit.value && selectedJudgment.value) {
      await JudgmentService.updateJudgment(selectedJudgment.value.id, params)
      toast.success('修改成功')
    } else {
      await JudgmentService.createJudgment(params)
      toast.success('新增成功')
    }

    closeDialog()
    loadJudgments()
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isSubmitting.value = false
  }
}

const confirmDelete = async () => {
  if (!selectedJudgment.value) return

  try {
    isDeleting.value = true
    await JudgmentService.deleteJudgment(selectedJudgment.value.id)
    toast.success('删除成功')
    closeDeleteDialog()
    loadJudgments()
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isDeleting.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadJudgments()
}

const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.judge = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
  handleSearch()
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadJudgments()
}

const closeDialog = () => {
  editDialog.value?.close()
}

const closeDeleteDialog = () => {
  deleteDialog.value?.close()
}

// 生命周期
onMounted(() => {
  loadStats()
  loadJudgments()
})
</script>

<style scoped>
.radial-progress {
  --thickness: 2px;
}
</style>
